<template>
  <md-page title="活动地图">
    <view class="page-map">
      <!-- 地图 -->
      <map
        id="myMap"
        show-location
        :scale="20"
        :style="{ width: '100%', height: 'calc(100vh - 44px - ' + data.statusBarHeight + ')' }"
        :latitude="data.latitude"
        :longitude="data.longitude"
        :markers="data.markers"
        :polyline="data.polyline"
        @markertap="markertap"
        @callouttap="markertap"
        @regionchange="regionchange">
        <!-- <cover-view slot="callout">
          <block v-for="item in data.markers" :key="item.id">
            <cover-view class="customCallout" :marker-id="item.id">
              <cover-view class="content">
                {{ item.point_name }}
              </cover-view>
              <cover-image class="icon" :src="item.customCallout.iconPath"></cover-image>
            </cover-view>
          </block>
        </cover-view> -->
      </map>
      <!-- 图例 -->
      <view class="legend">
        <block v-for="(item, index) in data.icon_list" :key="index">
          <view class="row" v-if="item.id != 4" @click="onChangeLegend(item)">
            <image class="img" :src="item.icon" mode="" />
            <view class="label">{{ item.name }}</view>
          </view>
        </block>
      </view>
      <!-- 回到当前位置 -->
      <view class="btns">
        <button @click="moveTargetCenterLocation" class="location-btn center-location">
          <image class="loc-icon" src="@/static/icons/re-location.png"></image>
        </button>
      </view>
      <!-- 刷新按钮 -->
      <image class="left-btns refresh" @click="handleRefresh" src="@/static/images/point/all.png"></image>
      <!-- 返回列表按钮 -->
      <!-- <view class="left-btns back" @click="handleBack">
        <md-icon name="back" height="90" width="90"></md-icon>
      </view> -->
      <image class="left-btns back" @click="handleBack" src="@/static/images/point/list.png"></image>
      <!-- 点位详情信息 -->
      <!-- <view v-if="data.info?.id" class="bottomRoomInfo">
        <view class="flex_col">
          <view class="title">{{ data.info.title }}</view>
          <view class="flex_row_center">
            <view class="flex_row_center flex_btw m-bottom-16">
              <text v-for="item in data.info.tags" :key="item" class="tag">{{ item }}</text>
            </view>
            <view class="btn" @click="handleOpenLocation">导航</view>
          </view>
        </view>
      </view> -->
    </view>
  </md-page>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { getWXUserLocation, calculateDistance, getLocation } from '@/utils/util';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { matchMapPoint } from '@/api';
import { PointType } from '@/common/enum';
import type { Match } from '@/api/data';

const data = reactive<any>({
  statusBarHeight: uni.getSystemInfoSync().statusBarHeight + 'px',
  latitude: null,
  longitude: null,
  markers: [],
  polyline: [],
  info: {},
  icon_list: [],
});
// 地图实例
const mapCtx = ref<any>(null);

// 处理打卡的方式
const _checkInMethod = (info: Match.Point.PointListData) => {
  // 打卡点1、补给点3、起点5、终点6
  if (info.type.includes('1') || info.type.includes('3') || info.type.includes('5') || info.type.includes('6')) {
    // 1：用户扫码 2：上传图片 3：二维码打卡 4:ar打卡
    if ([4].includes(info.dk_type)) {
      // AR打卡
      uni.navigateTo({
        url: `/pages/ar/ar-checkin?point_id=${info.id}&active_id=${data.active_id}`,
      });
    } else {
      if ([1, 3].includes(info.dk_type)) {
        uni.navigateTo({
          url: `/pages/other/match/points/scan-code?point_id=${info.id}`,
        });
      } else {
        uni.navigateTo({
          url: '/pages/other/match/points/upload-image?point_id=' + info.id,
        });
      }
    }
    
    
  }
};

// 测试距离
// flag 是否开启点击确认跳转打卡列表页面
const _checkDistance = (params: { markerId?: number; item?: any }, flag?: boolean) => {
  let info: any;
  if (params?.item) {
    info = params.item;
  } else {
    info = data.markers.find((item: { id: any }) => item.id == params?.markerId);
  }
  // 测距离
  getLocation()
    .then(res => {
      const distanceKm = calculateDistance(
        res.latitude,
        res.longitude,
        Number(info.latitude),
        Number(info.longitude),
        'm'
      );
      if (info.distance !== -1 && distanceKm >= info.distance) {
        uni.showModal({
          title: '提示',
          content: '您未到打卡区域,距离：' + distanceKm.toFixed(4) + '米',
          showCancel: false,
          success: res => {
            if (res.confirm) {
              if (!!flag) {
                uni.redirectTo({
                  url: '/pages/activity/detail?active_id=' + data.active_id,
                });
              }
            }
          },
        });
        return;
      }
      // 处理打卡方式
      _checkInMethod(info);
    })
    .catch(err => {
      uni.showModal({
        title: '提示',
        content: '获取定位失败',
        showCancel: false,
        success: res => {
          if (res.confirm) {
            if (!!flag) {
              uni.redirectTo({
                url: '/pages/activity/detail?active_id=' + data.active_id,
              });
            }
          }
        },
      });
    });
};

// 点击market回调
function markertap(r: { detail: { markerId: any } }) {
  const { markerId } = r.detail;
  _checkDistance({ markerId });
}

// 地图视野变化回调
function regionchange() {
  if (data.info?.id) {
    data.info = {};
  }
}

// 移动到当前经纬度位置
const moveTargetCenterLocation = () => {
  // console.log('移动到当前经纬度位置');
  // 移动到当前定位的中心区域位置
  mapCtx.value.moveToLocation();
};

// 导航
function handleOpenLocation() {
  const { latitude, longitude } = data.info;
  uni.showModal({
    title: '提示',
    content: '是否前往导航？',
    complete: res => {
      if (res.confirm) {
        uni.openLocation({
          latitude,
          longitude,
          scale: 20,
        });
      }
    },
  });
}

// 刷新
function handleRefresh() {
  getMapList();
}

// 返回打卡点列表
function handleBack() {
  uni.navigateTo({
    url: '/pages/other/match/points/index?active_id=' + data.active_id,
  });
}

/**
 * 接口相关
 */

const getMapList = async (chooseId = '') => {
  // type: 1：打卡点 2：主题点 3：补给点 4：空白点 5: 起点 6: 终点 7: 互动点
  // 比赛列表
  uni.showLoading({
    title: '加载中...',
    mask: true,
  });
  let active_id = data.active_id;
  try {
    const res = await matchMapPoint({ active_id });
    // 起点未打卡，跳转起点打卡页
    if (res.data.start_status === 1) {
      if(res.data?.pointList?.length > 0) {
        const item = res.data?.pointList?.[0];
        _checkDistance({ item }, true);
        // 处理打卡方式
        // _checkInMethod(item);
        uni.hideLoading();
        return;
      } else {
        uni.showModal({
          title: '提示',
          content: '当前路线未设置打卡点',
          showCancel: false,
          success: res => {
            return; 
          },
        });
      }
    }
    // 处理点位图标
    const _markers = res.data?.pointList?.map(item => {
      // 空白点
      let iconPath = res.data?.iconList?.[4];
      // 补给点
      if (item.type.includes('3')) {
        iconPath = res.data?.iconList?.[3];
      }
      // 打卡点
      if (item.type.includes('1')) {
        iconPath = res.data?.iconList?.[1];
      }
      // 主题点
      if (item.type.includes('2')) {
        iconPath = res.data?.iconList?.[2];
      }
      // 互动点
      if (item.type.includes('7')) {
        iconPath = res.data?.iconList?.[7];
      }
      // 起点
      if (item.type.includes('5')) {
        iconPath = res.data?.iconList?.[5];
      }
      // 终点
      if (item.type.includes('6')) {
        iconPath = res.data?.iconList?.[6];
      }
      if (chooseId) {
        iconPath = res.data?.iconList?.[Number(chooseId)];
      }

      return chooseId
        ? {
            ...item,
            latitude: Number(item.latitude),
            longitude: Number(item.longitude),
            iconPath,
            title: item.point_name,
            alpha: item.type.includes(chooseId) ? 1 : 0,
            callout: item.type.includes(chooseId)
              ? {
                  // 仅跟点击的图例相同的显示，其余的都隐藏
                  content: item.point_name,
                  display: 'ALWAYS',
                  bgColor: 'transparent',
                  fontSize: 18,
                }
              : {},
            width: 25,
            height: 25,
          }
        : {
            ...item,
            latitude: Number(item.latitude),
            longitude: Number(item.longitude),
            iconPath,
            title: item.point_name,
            alpha: item.type == '4' ? 0 : 1,
            callout:
              item.type != '4'
                ? {
                    // 除空白点外，名称都显示
                    content: item.point_name,
                    display: 'ALWAYS',
                    bgColor: 'transparent',
                    fontSize: 18,
                  }
                : {},
            width: 25,
            height: 25,
          };
    });
    data.markers = _markers;
    // 连线的样式
    data.polyline =
      res.data?.is_fine_food == 1
        ? []
        : [{ points: _markers, width: 6, color: '#51C8F9', arrowLine: true, borderWidth: 4, borderColor: '#3280C1' }];

    // 图例处理
    let icon_list = [];
    if (Object.keys(res.data.iconList || {})?.length > 0) {
      for (let [key, value] of Object.entries(res.data.iconList)) {
        icon_list.push({ id: key, icon: value, name: PointType[key] });
      }
    }
    data.icon_list = icon_list;
  } catch (error) {}
  uni.hideLoading();
};

// 点击某个图例，隐藏掉别的类型的图例
const onChangeLegend = (item: any) => {
  getMapList(item.id);
};

onLoad(options => {
  data.active_id = options?.active_id;
  getWXUserLocation().then(res => {
    data.latitude = res.latitude;
    data.longitude = res.longitude;
  });

  // 选择当前定位位置
  // wx.chooseLocation();
});

onMounted(() => {
  mapCtx.value = uni.createMapContext('myMap');
});
onShow(() => {
  handleRefresh();
});
</script>

<style lang="scss" scoped>
.page-map {
  position: relative;
}

.center-location {
  display: flex;
  align-items: center;
  justify-content: center;
}

.customCallout {
  display: flex;
  flex-direction: column;
  align-items: center;
  .content {
    font-size: 18px;
    text-shadow: 1px 1px 2px black, 0 0 1em #ffa500, 0 0 0.2em #ffa500;
  }
  .icon {
    width: 25px;
    height: 25px;
    margin-top: 8rpx;
  }
}

/* 图例 */
.legend {
  position: fixed;
  right: 20rpx;
  bottom: 200rpx;
  // padding: 6rpx 16rpx;
  // border-radius: 6rpx;
}

.legend .row {
  display: flex;
  align-items: center;
  font-size: 35rpx;
  margin-bottom: 32rpx;
  border-radius: 30rpx;
  padding: 6rpx 16rpx;
  background: white;
}

.legend .row:not(:last-of-type) {
  margin-bottom: 10rpx;
}

.legend .img {
  width: 40rpx;
  height: 40rpx;
  margin-right: 8rpx;
}

.btns {
  position: fixed;
  bottom: 505rpx;
  left: 22rpx;
}

.left-btns {
  position: fixed;
  bottom: 370rpx;
  left: 10rpx;
}

.refresh {
  display: flex;
  align-items: center;
  justify-content: center;
  bottom: 395rpx;
  border-radius: 50%;
  width: 90rpx;
  height: 90rpx;
  background: #fff;
}

.back {
  bottom: 285rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  width: 90rpx;
  height: 90rpx;
  background: #fff;
}

.btns .location-btn {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  background: #fff;
  padding: 0;
}

.btns .loc-icon {
  width: 44rpx;
  height: 44rpx;
}

.bottomRoomInfo .title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333333;
  line-height: 31rpx;
  margin-bottom: 16rpx;
}

.bottomRoomInfo .tag {
  height: 40rpx;
  line-height: 40rpx;
  text-align: center;
  border-radius: 10rpx;
  padding: 0 18rpx;
  box-sizing: border-box;
  background: #ededed;
  color: #666666;
  margin-right: 16rpx;
}

.bottomRoomInfo .content {
  height: 132rpx;
}

.bottomRoomInfo .btn {
  min-width: 188rpx;
  height: 63rpx;
  line-height: 63rpx;
  text-align: center;
  background: #e64627;
  border-radius: 28rpx;
  font-size: 30rpx;
  font-weight: bold;
  color: #ffffff;
  padding: 0 30rpx;
}

.bottomRoomInfo {
  position: absolute;
  bottom: $safe-bottom;
  left: 30rpx;
  width: 689rpx;
  max-height: 240rpx;
  background: #ffffff;
  box-shadow: 0rpx 4rpx 4rpx 0rpx rgba(102, 102, 102, 0.22);
  border-radius: 10rpx;
  padding: 23rpx 24rpx 19rpx;
}
</style>
